# -*- coding: utf-8 -*-
import base64

import cv2
import numpy as npy


class ImageTools:
	
	def __init__(self, scaleFactor=1.15, minNeighbors=5, minSize=(5, 5), image_size=240):
		# 人脸分类器
		self.cascade_cassifier = cv2.CascadeClassifier("face_recognition/recognition/cascade_cassifier/haarcascade_frontalface_alt.xml")
		self.recognizer = cv2.face.LBPHFaceRecognizer_create()
		self.scaleFactor = scaleFactor
		self.minNeighbors = minNeighbors
		self.minSize = minSize
		self.image_size = image_size
	
	def resize_image(self, image, height=None, width=None):
		"""
		图片处理服务：调整图片的大小\n
		@Return image
		"""
		if height is None:
			height = self.image_size
		if width is None:
			width = self.image_size
		top, bottom, left, right = (0, 0, 0, 0)
		# 获取图像尺寸
		h, w, _ = image.shape
		# 对于长宽不相等的图片，找到最长的一边
		longest_edge = max(h, w)
		# 计算短边需要增加多上像素宽度使其与长边等长
		if h < longest_edge:
			dh = longest_edge - h
			top = dh // 2
			bottom = dh - top
		elif w < longest_edge:
			dw = longest_edge - w
			left = dw // 2
			right = dw - left
		# RGB颜色
		BLACK = [0, 0, 0]
		# 给图像增加边界，是图片长、宽等长，cv2.BORDER_CONSTANT指定边界颜色由value指定
		constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)
		# 调整图像大小并返回
		return cv2.resize(constant, (height, width))
	
	def get_feature_from_base64(self, base64_content):
		"""
		识别base64_content图片中的人脸信息，并且提取特征数据\n
		:param base64_content:人脸图像base64编码\n
		:return:this_face(人脸特征数据)
		"""
		imgData = base64.b64decode(base64_content)
		npy_arr = npy.fromstring(imgData, npy.uint8)
		img_array = cv2.imdecode(npy_arr, cv2.IMREAD_COLOR)
		# 灰度
		img_gray_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
		face_area = self.cascade_cassifier.detectMultiScale(img_gray_array, scaleFactor=self.scaleFactor,
		                                                    minNeighbors=self.minNeighbors, minSize=self.minSize)
		if face_area is not None and len(face_area) > 0:
			for (x, y, w, h) in face_area:
				this_face = img_gray_array[y:y + h, x:x + w]
				return this_face
		return None
	
	def get_feature_from_image(self, image):
		"""
		识别图片中的人脸信息，并且提取特征数据\n
		:param image:图像数据（二维数组）\n
		:return:this_face(人脸特征数据)
		"""
		image = self.resize_image(image)
		# 灰度
		img_gray_array = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
		face_area = self.cascade_cassifier.detectMultiScale(img_gray_array, scaleFactor=self.scaleFactor,
		                                                    minNeighbors=self.minNeighbors, minSize=self.minSize)
		if face_area is not None and len(face_area) > 0:
			for (x, y, w, h) in face_area:
				this_face = img_gray_array[y:y + h, x:x + w]
				return this_face
		else:
			print(">>>>>>>>>>>>>>>>>未能从传入的图像信息中检测到人脸！")
		return None
	
	def get_feature_from_pic(self, filepath):
		"""
		识别图片中的人脸信息，并且提取特征数据\n
		:param image:图像数据（二维数组）\n
		:return:this_face(人脸特征数据)
		"""
		img_array = cv2.imread(filepath)
		# 灰度
		img_gray_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
		face_area = self.cascade_cassifier.detectMultiScale(img_gray_array, scaleFactor=self.scaleFactor,
		                                                    minNeighbors=self.minNeighbors, minSize=self.minSize)
		if face_area is not None and len(face_area) > 0:
			for (x, y, w, h) in face_area:
				this_face = img_gray_array[y:y + h, x:x + w]
				return this_face
		else:
			print(">>>>>>>>>>>>>>>>>未能从传入的图像信息中检测到人脸！")
		return None
